package com.pet.platform.util;

import com.pet.platform.entity.User;
import com.pet.platform.exception.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class SecurityUtils {
    
    private static final String TOKEN_HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";
    private static ThreadLocal<User> currentUser = new ThreadLocal<>();
    
    /**
     * 获取当前登录用户ID
     */
    public static Long getCurrentUserId() {
        return getLoginUser().getId();
    }

    /**
     * 获取当前登录用户名
     */
    public static String getCurrentUsername() {
        return getLoginUser().getUsername();
    }

    /**
     * 获取当前登录用户
     */
    public static User getLoginUser() {
        User user = currentUser.get();
        if (user == null) {
            throw new BusinessException("用户未登录");
        }
        return user;
    }

    /**
     * 设置当前登录用户
     */
    public static void setLoginUser(User user) {
        currentUser.set(user);
    }

    /**
     * 清除当前登录用户
     */
    public static void clearLoginUser() {
        currentUser.remove();
    }

    /**
     * 判断当前用户是否已登录
     */
    public static boolean isAuthenticated() {
        try {
            return getLoginUser() != null;
        } catch (BusinessException e) {
            return false;
        }
    }

    /**
     * 判断当前用户是否具有指定角色
     */
    public static boolean hasRole(String role) {
        try {
            User user = getLoginUser();
            return role.equals(user.getRole());
        } catch (BusinessException e) {
            return false;
        }
    }

    /**
     * 判断当前用户是否是管理员
     */
    public static boolean isAdmin() {
        return hasRole("ADMIN");
    }

    /**
     * 获取当前请求的token
     */
    public static String getToken() {
        HttpServletRequest request = getRequest();
        String token = request.getHeader(TOKEN_HEADER);
        if (token != null && token.startsWith(TOKEN_PREFIX)) {
            return token.substring(TOKEN_PREFIX.length());
        }
        return null;
    }

    private static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new BusinessException("获取请求上下文失败");
        }
        return attributes.getRequest();
    }
} 